package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.remark.RemarkClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author lyh
 * @since 2024-12-11
 */
@Service
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    @Autowired
    @Lazy
    private IInteractionQuestionService questionService;
    @Autowired
    private UserClient userClient;

    /**
     * 新增回答或者评论
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addReply(ReplyDTO dto) {
       if(dto==null){
           throw new BadRequestException("参数异常");
       }
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        reply.setUserId(UserContext.getUser());
        boolean save = this.save(reply);
        if(!save){
            throw new DbException("添加回答或者评论失败");
        }
        //判断是否是回答，是回答id为空
       if(ObjectUtils.isEmpty(dto.getAnswerId())){
          //回答
           //修改最近一次回答的id
           //添加回答次数
           boolean update = questionService.lambdaUpdate()
                   .set(InteractionQuestion::getLatestAnswerId, reply.getId())
                   .setSql("answer_times=answer_times+1")
                   .eq(InteractionQuestion::getId, dto.getQuestionId())
                   .update();
           if(!update){
               throw new DbException("修改问题表失败");
           }
       }else{
           //评论   累加回答下评论次数
           boolean update = this.lambdaUpdate()
                   .setSql("reply_times=reply_times+1")
                   .eq(InteractionReply::getId, dto.getTargetReplyId())
                   .update();
           if(!update){
               throw new DbException("修改评论表失败");
           }
       }
       //判断提交评论的用户是否是学生
      if(dto.getIsStudent()){
          //如果是标记问题状态为未查看
          boolean update = questionService.lambdaUpdate()
                  .set(InteractionQuestion::getStatus, QuestionStatus.UN_CHECK.getValue())
                  .eq(InteractionQuestion::getId, dto.getQuestionId())
                  .update();
          if(!update){
              throw new DbException("修改问题表失败");
          }
      }

    }
   @Autowired
   private RemarkClient remarkClient;
    @Override
    public PageDTO<ReplyVO> pageQuery(ReplyPageQuery query) {
        //判断问题id和回答id是否至少有一个
        if(ObjectUtils.isEmpty(query.getQuestionId())&&ObjectUtils.isEmpty(query.getAnswerId())){
            throw new BadRequestException("问题id和回答id至少有一个");
        }
        //分页查询
        Page<InteractionReply> page = this.lambdaQuery()
                .eq(query.getAnswerId() != null, InteractionReply::getAnswerId, query.getAnswerId())
                .eq(query.getQuestionId() != null, InteractionReply::getQuestionId, query.getQuestionId())
                .eq(InteractionReply::getHidden,false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        //分页结果
        List<InteractionReply> records = page.getRecords();
        //分页结果为空
        if(CollUtils.isEmpty(records)){
            return PageDTO.empty(0L,0L);
        }
        Set<Long> userId=new HashSet<>();
        List<Long> replyId=new ArrayList<>();
        for (InteractionReply record : records) {
            userId.add(record.getUserId());
            userId.add(record.getTargetUserId());
            replyId.add(record.getId());
        }
        //查询点赞的id
        Set<Long> bizLiked = remarkClient.isBizLiked(replyId);
        Set<Long> set = userId.stream().filter(id -> id != null).collect(Collectors.toSet());
        List<UserDTO> user = userClient.queryUserByIds(set);
        Map<Long, UserDTO> map = user.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        //补充属性
        List<ReplyVO> list = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO vo = BeanUtils.copyBean(record, ReplyVO.class);
            if(!record.getAnonymity()) {
                UserDTO userDTO = map.getOrDefault(record.getUserId(), new UserDTO());
                if (userDTO != null) {
                    vo.setUserName(userDTO.getName());
                    vo.setUserType(userDTO.getType());
                    vo.setUserIcon(userDTO.getIcon());
                }
            }
            if(bizLiked.contains(record.getId())){
                vo.setLiked(true);
            }else{
                vo.setLiked(false);
            }
            if(record.getTargetReplyId()!=null) {
                UserDTO target = map.getOrDefault(record.getTargetUserId(), new UserDTO());
                vo.setTargetUserName(target.getName());
            }
            Integer count = this.lambdaQuery()
                    .eq(InteractionReply::getHidden, false)
                    .eq(InteractionReply::getTargetReplyId, record.getId())
                    .count();
            vo.setReplyTimes(count);
            list.add(vo);
        }
        return PageDTO.of(page,list);
    }

    @Override
    public PageDTO<ReplyVO> pageQueryAdmin(ReplyPageQuery query) {
        //判断问题id和回答id是否至少有一个
        if(ObjectUtils.isEmpty(query.getQuestionId())&&ObjectUtils.isEmpty(query.getAnswerId())){
            throw new BadRequestException("问题id和回答id至少有一个");
        }
        //分页查询
        Page<InteractionReply> page = this.lambdaQuery()
                .eq(query.getAnswerId() != null, InteractionReply::getAnswerId, query.getAnswerId())
                .eq(query.getQuestionId() != null, InteractionReply::getQuestionId, query.getQuestionId())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        //分页结果
        List<InteractionReply> records = page.getRecords();
        //分页结果为空
        if(CollUtils.isEmpty(records)){
            return PageDTO.empty(0L,0L);
        }
        Set<Long> userId=new HashSet<>();
        List<Long> replyId=new ArrayList<>();
        for (InteractionReply record : records) {
            userId.add(record.getUserId());
            userId.add(record.getTargetUserId());
            //replyId.add(record.getId());
        }
        Set<Long> bizLiked = remarkClient.isBizLiked(replyId);
        Set<Long> set = userId.stream().filter(id -> id != null).collect(Collectors.toSet());
        List<UserDTO> user = userClient.queryUserByIds(set);
        Map<Long, UserDTO> map = user.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        //补充属性
        List<ReplyVO> list = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO vo = BeanUtils.copyBean(record, ReplyVO.class);
                UserDTO userDTO = map.getOrDefault(record.getUserId(), new UserDTO());
                if (userDTO != null) {
                    vo.setUserName(userDTO.getName());
                    vo.setUserType(userDTO.getType());
                    vo.setUserIcon(userDTO.getIcon());
                }

            if(bizLiked.contains(record.getId())){
                vo.setLiked(true);
            }else{
                vo.setLiked(false);
            }
            if(record.getTargetReplyId()!=null) {
                UserDTO target = map.getOrDefault(record.getTargetUserId(), new UserDTO());
                vo.setTargetUserName(target.getName());
            }
            list.add(vo);
        }
        return PageDTO.of(page,list);
    }

    @Override
    public void hiddenReply(Long id, Boolean hidden) {
        InteractionReply reply = this.getById(id);
        if(ObjectUtils.isEmpty(reply)){
            throw new BadRequestException("评论或回答不存在");
        }
        if(ObjectUtils.equal(reply.getHidden(),hidden)){
            throw new BadRequestException("已是想要状态，请勿重复操作");
        }
        boolean update = this.lambdaUpdate()
                .set(InteractionReply::getHidden, hidden)
                .eq(InteractionReply::getId, id)
                .update();
        if(!update){
            throw new DbException("修改评论或回答失败");
        }
    }
}